package com.disease.api.service.service;

import com.disease.api.service.config.JwtService;
import com.disease.api.service.entity.BaseDept;
import com.disease.api.service.entity.BaseUser;
import com.disease.api.service.entity.EmrBaseUser;
import com.disease.api.service.entity.eumns.RoleEnum;
import com.disease.api.service.mapper.BaseDeptMapper;
import com.disease.api.service.mapper.EmrUserMapper;
import com.disease.api.service.mapper.UserMapper;
import com.disease.api.service.model.LoginUser;
import com.disease.api.service.model.ResponseResult;
import com.disease.api.service.model.response.BaseUserResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LoginService {

    private static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmrUserMapper emrUserMapper;

    @Autowired
    private BaseDeptMapper baseDeptMapper;

    @PostConstruct
    public void taskSyncUser() {
        if(userMapper.selectCount()<5){
            log.info("同步用户数据开始");
            List<BaseUser> baseUsers=new ArrayList<>();
            List<EmrBaseUser> emrBaseUsers = emrUserMapper.selectByQuery(new EmrBaseUser());
            for (EmrBaseUser emrBaseUser : emrBaseUsers){
                if(!emrBaseUser.getUsername().equals("admin")){
                    BaseUser baseUser = new BaseUser();
                    baseUser.setOrgCode(Optional.ofNullable(emrBaseUser.getOrgCode()).orElse(""));
                    baseUser.setDeptCode(Optional.ofNullable(emrBaseUser.getDeptCode()).orElse(""));
                    baseUser.setUsername(Optional.ofNullable(emrBaseUser.getLoginName()).orElse(""));
                    baseUser.setPassword("123456");
                    baseUser.setDoctorId(Optional.ofNullable(emrBaseUser.getId()).orElse(""));
                    baseUser.setIdCardTypeCode(Optional.ofNullable(emrBaseUser.getIdCardTypeCode()).orElse("01"));
                    baseUser.setIdCard(Optional.ofNullable(emrBaseUser.getIdCard()).orElse(""));
                    baseUser.setTel(Optional.ofNullable(emrBaseUser.getTel()).orElse(""));
                    baseUser.setPhysicianNo(Optional.ofNullable(emrBaseUser.getPhysicianNo()).orElse("0"));
                    baseUser.setLoginName(Optional.ofNullable(emrBaseUser.getUsername()).orElse(""));
                    baseUser.setUserTypeCode(Optional.ofNullable(emrBaseUser.getUserTypeCode()).orElse(""));
                    baseUser.setRole(1);
                    baseUsers.add(baseUser);
                }
            }
            userMapper.batchInsert(baseUsers);
        }
    }


    public ResponseResult<BaseUserResponse> Login(LoginUser user) {
        BaseUserResponse baseUserResponse = new BaseUserResponse();
        BaseUser userInfo = userMapper.findUser(user.getUsername(), user.getPassword());
        if (null != userInfo) {
            BeanUtils.copyProperties(userInfo,baseUserResponse);
            if(Optional.ofNullable(userInfo.getDeptCode()).isPresent() && !StringUtils.isBlank(userInfo.getDeptCode())){
                List<BaseDept> deptNames = baseDeptMapper.findDeptNamesByDeptCodes(Arrays.asList(userInfo.getDeptCode().split(",")));
                if(null!=deptNames&& !deptNames.isEmpty()){
                    baseUserResponse.setDeptNames(deptNames.stream().map(BaseDept::getDeptName).collect(Collectors.toList()));
                }
            }
            //如果角色是医生，绑定国家前置软件账号ID
            String token = JwtService.generateToken(userInfo.getId(), userInfo);
            baseUserResponse.setAuthorization(token);
            return ResponseResult.success(baseUserResponse);
        } else {
            return ResponseResult.fail("用户名或密码错误");
        }
    }

}
